/**
 * 校园二手交易平台 - 商品API服务
 * 提供完整的商品管理功能，支持Mock模式和真实API模式
 */

import BaseService, { ApiResponse, PaginatedResponse } from './baseService';
import {
  Product,
  ProductFormData,
  ProductQueryParams,
  ProductListResponse,
  ProductStats,
  ProductOperationResult,
  ProductSearchSuggestion,
  ProductFavorite,
  ProductCategory,
  ProductCondition,
  ProductStatus,
  DEFAULT_PRODUCT_QUERY_PARAMS,
  validateProductData,
} from '../types/product';

/**
 * 商品服务类
 */
export class ProductService extends BaseService {
  private useMock: boolean = process.env.NODE_ENV === 'development';
  
  constructor(baseURL?: string) {
    super(baseURL || '/api/products');
  }

  /**
   * 获取商品列表（支持分页、筛选、排序）
   */
  async getProducts(params: ProductQueryParams = {}): Promise<ProductListResponse> {
    const queryParams = { ...DEFAULT_PRODUCT_QUERY_PARAMS, ...params };
    
    if (this.useMock) {
      return this.getMockProducts(queryParams);
    }
    
    return this.get<ProductListResponse>('/list', queryParams);
  }

  /**
   * 获取商品详情
   */
  async getProduct(id: string): Promise<Product> {
    if (this.useMock) {
      return this.getMockProduct(id);
    }
    
    return this.get<Product>(`/detail/${id}`);
  }

  /**
   * 发布商品
   */
  async createProduct(productData: ProductFormData): Promise<ProductOperationResult> {
    // 验证商品数据
    if (!validateProductData(productData)) {
      return {
        success: false,
        message: '商品数据不完整或格式错误',
        error: 'VALIDATION_ERROR',
      };
    }

    if (this.useMock) {
      return this.createMockProduct(productData);
    }
    
    return this.post<ProductOperationResult>('/create', productData);
  }

  /**
   * 编辑商品
   */
  async updateProduct(id: string, productData: Partial<ProductFormData>): Promise<ProductOperationResult> {
    if (this.useMock) {
      return this.updateMockProduct(id, productData);
    }
    
    return this.put<ProductOperationResult>(`/update/${id}`, productData);
  }

  /**
   * 删除商品
   */
  async deleteProduct(id: string): Promise<ProductOperationResult> {
    if (this.useMock) {
      return this.deleteMockProduct(id);
    }
    
    return this.delete<ProductOperationResult>(`/delete/${id}`);
  }

  /**
   * 上架/下架商品
   */
  async toggleProductStatus(id: string, status: ProductStatus): Promise<ProductOperationResult> {
    if (this.useMock) {
      return this.toggleMockProductStatus(id, status);
    }
    
    return this.patch<ProductOperationResult>(`/status/${id}`, { status });
  }

  /**
   * 获取我的商品列表
   */
  async getMyProducts(params: Omit<ProductQueryParams, 'onlyActive'> = {}): Promise<ProductListResponse> {
    if (this.useMock) {
      return this.getMockMyProducts(params);
    }
    
    return this.get<ProductListResponse>('/my-products', params);
  }

  /**
   * 搜索商品
   */
  async searchProducts(keyword: string, params?: Omit<ProductQueryParams, 'keyword'>): Promise<ProductListResponse> {
    const searchParams = { keyword, ...params };
    
    if (this.useMock) {
      return this.searchMockProducts(keyword, params);
    }
    
    return this.get<ProductListResponse>('/search', searchParams);
  }

  /**
   * 获取搜索建议
   */
  async getSearchSuggestions(keyword: string): Promise<ProductSearchSuggestion[]> {
    if (this.useMock) {
      return this.getMockSearchSuggestions(keyword);
    }
    
    return this.get<ProductSearchSuggestion[]>('/search/suggestions', { keyword });
  }

  /**
   * 获取商品统计信息
   */
  async getProductStats(): Promise<ProductStats> {
    if (this.useMock) {
      return this.getMockProductStats();
    }
    
    return this.get<ProductStats>('/stats');
  }

  /**
   * 收藏商品
   */
  async favoriteProduct(productId: string): Promise<ProductOperationResult> {
    if (this.useMock) {
      return this.favoriteMockProduct(productId);
    }
    
    return this.post<ProductOperationResult>(`/favorite/${productId}`);
  }

  /**
   * 取消收藏商品
   */
  async unfavoriteProduct(productId: string): Promise<ProductOperationResult> {
    if (this.useMock) {
      return this.unfavoriteMockProduct(productId);
    }
    
    return this.delete<ProductOperationResult>(`/favorite/${productId}`);
  }

  /**
   * 获取我的收藏列表
   */
  async getMyFavorites(params?: { page?: number; pageSize?: number }): Promise<{
    favorites: ProductFavorite[];
    total: number;
  }> {
    if (this.useMock) {
      return this.getMockMyFavorites(params);
    }
    
    return this.get<{ favorites: ProductFavorite[]; total: number }>('/favorites/my', params);
  }

  // ========== Mock 数据方法 ==========

  /**
   * 生成模拟商品数据
   */
  private generateMockProducts(count: number = 50): Product[] {
    const mockProducts: Product[] = [];
    const categories = Object.values(ProductCategory);
    const conditions = Object.values(ProductCondition);
    const statuses = Object.values(ProductStatus);
    const schools = ['清华大学', '北京大学', '复旦大学', '上海交通大学', '浙江大学', '南京大学'];
    
    for (let i = 1; i <= count; i++) {
      const category = categories[Math.floor(Math.random() * categories.length)];
      const condition = conditions[Math.floor(Math.random() * conditions.length)];
      const status = statuses[Math.floor(Math.random() * statuses.length)];
      
      mockProducts.push({
        id: `product_${i}`,
        title: `${this.getProductTitleByCategory(category)} ${i}`,
        description: `这是${this.getProductTitleByCategory(category)}的详细描述，品质良好，价格实惠。`,
        price: Math.floor(Math.random() * 500) + 10,
        originalPrice: Math.floor(Math.random() * 800) + 50,
        category,
        condition,
        transactionMethod: Math.random() > 0.5 ? 'face_to_face' : 'both',
        images: [
          {
            id: `img_${i}_1`,
            url: `https://picsum.photos/400/300?${i % 100}`,
            thumbnailUrl: `https://picsum.photos/200/150?${i % 100}`,
            isCover: true,
            uploadedAt: new Date(),
          },
        ],
        location: {
          school: schools[Math.floor(Math.random() * schools.length)],
          campus: '主校区',
          address: '学生宿舍区',
        },
        publisher: {
          userId: `user_${Math.floor(Math.random() * 100)}`,
          username: `学生${Math.floor(Math.random() * 1000)}`,
          avatar: `https://i.pravatar.cc/150?img=${Math.floor(Math.random() * 70)}`,
          isStudentVerified: Math.random() > 0.3,
          school: schools[Math.floor(Math.random() * schools.length)],
        },
        publishedAt: new Date(Date.now() - Math.floor(Math.random() * 30 * 24 * 60 * 60 * 1000)),
        updatedAt: new Date(),
        status,
        viewCount: Math.floor(Math.random() * 1000),
        favoriteCount: Math.floor(Math.random() * 100),
        inquiryCount: Math.floor(Math.random() * 50),
        tags: ['校园', '二手', '实惠', '学生'],
        isNegotiable: Math.random() > 0.5,
        isFreeShipping: Math.random() > 0.7,
        shippingFee: Math.random() > 0.7 ? Math.floor(Math.random() * 20) + 5 : undefined,
        stock: status === ProductStatus.SOLD ? 0 : Math.floor(Math.random() * 5) + 1,
        isReturnable: Math.random() > 0.8,
      });
    }
    
    return mockProducts;
  }

  /**
   * 根据类别生成商品标题
   */
  private getProductTitleByCategory(category: ProductCategory): string {
    const titles = {
      [ProductCategory.TEXTBOOKS]: ['高等数学教材', '英语四级词汇', '程序设计教程', '经济学原理'],
      [ProductCategory.ELECTRONICS]: ['二手笔记本电脑', '智能手机', '蓝牙耳机', '平板电脑'],
      [ProductCategory.CLOTHING]: ['春秋季外套', '运动鞋', '牛仔裤', '卫衣'],
      [ProductCategory.DAILY_GOODS]: ['保温杯', '台灯', '收纳箱', '床上用品'],
      [ProductCategory.SPORTS]: ['篮球', '羽毛球拍', '瑜伽垫', '运动手表'],
      [ProductCategory.STATIONERY]: ['笔记本', '文具套装', '计算器', '书架'],
      [ProductCategory.DORMITORY]: ['床垫', '书桌', '衣柜', '电风扇'],
      [ProductCategory.OTHER]: ['闲置物品', '小礼品', '手工艺品', '收藏品'],
    };
    
    const categoryTitles = titles[category] || ['校园闲置物品'];
    return categoryTitles[Math.floor(Math.random() * categoryTitles.length)];
  }

  /**
   * Mock: 获取商品列表
   */
  private async getMockProducts(params: ProductQueryParams): Promise<ProductListResponse> {
    await this.delay(300); // 模拟网络延迟
    
    let mockProducts = this.generateMockProducts(100);
    
    // 应用筛选条件
    if (params.keyword) {
      mockProducts = mockProducts.filter(product => 
        product.title.includes(params.keyword!) || 
        product.description.includes(params.keyword!)
      );
    }
    
    if (params.category) {
      mockProducts = mockProducts.filter(product => product.category === params.category);
    }
    
    if (params.condition) {
      mockProducts = mockProducts.filter(product => product.condition === params.condition);
    }
    
    if (params.school) {
      mockProducts = mockProducts.filter(product => product.location.school === params.school);
    }
    
    if (params.onlyActive) {
      mockProducts = mockProducts.filter(product => product.status === ProductStatus.ACTIVE);
    }
    
    // 应用排序
    if (params.sortBy) {
      mockProducts.sort((a, b) => {
        const order = params.sortOrder === 'asc' ? 1 : -1;
        switch (params.sortBy) {
          case 'price':
            return (a.price - b.price) * order;
          case 'publishedAt':
            return (a.publishedAt.getTime() - b.publishedAt.getTime()) * order;
          case 'viewCount':
            return (a.viewCount - b.viewCount) * order;
          case 'favoriteCount':
            return (a.favoriteCount - b.favoriteCount) * order;
          default:
            return 0;
        }
      });
    }
    
    // 分页处理
    const page = params.page || 1;
    const pageSize = params.pageSize || 20;
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedProducts = mockProducts.slice(startIndex, endIndex);
    
    return {
      products: paginatedProducts,
      total: mockProducts.length,
      currentPage: page,
      totalPages: Math.ceil(mockProducts.length / pageSize),
      pageSize,
    };
  }

  /**
   * Mock: 获取商品详情
   */
  private async getMockProduct(id: string): Promise<Product> {
    await this.delay(200);
    
    // 如果ID格式符合product_数字的模式，生成对应的模拟商品
    if (id.startsWith('product_')) {
      const mockProducts = this.generateMockProducts(100);
      const product = mockProducts.find(p => p.id === id);
      
      if (product) {
        return product;
      }
    }
    
    // 如果没找到对应ID的商品，生成一个指定ID的模拟商品
    const categories = Object.values(ProductCategory);
    const conditions = Object.values(ProductCondition);
    const statuses = Object.values(ProductStatus);
    const schools = ['清华大学', '北京大学', '复旦大学', '上海交通大学', '浙江大学', '南京大学'];
    
    const category = categories[Math.floor(Math.random() * categories.length)];
    const condition = conditions[Math.floor(Math.random() * conditions.length)];
    const status = statuses[Math.floor(Math.random() * statuses.length)];
    const school = schools[Math.floor(Math.random() * schools.length)];
    
    const mockProduct: Product = {
      id: id,
      title: `商品 ${id}`,
      description: `这是商品 ${id} 的详细描述，品质良好，价格实惠。`,
      price: Math.floor(Math.random() * 500) + 10,
      originalPrice: Math.floor(Math.random() * 800) + 50,
      category,
      condition,
      transactionMethod: Math.random() > 0.5 ? 'face_to_face' : 'both',
      images: [
        {
          id: `${id}_img_1`,
          url: `https://picsum.photos/400/300?${this.hashCode(id) % 100}`,
          thumbnailUrl: `https://picsum.photos/200/150?${this.hashCode(id) % 100}`,
          isCover: true,
          uploadedAt: new Date(),
        },
      ],
      location: {
        school,
        campus: '主校区',
        address: '学生宿舍区',
      },
      publisher: {
        userId: `user_${Math.floor(Math.random() * 100)}`,
        username: `学生${Math.floor(Math.random() * 1000)}`,
        avatar: `https://i.pravatar.cc/150?img=${Math.floor(Math.random() * 70)}`,
        isStudentVerified: Math.random() > 0.3,
        school,
      },
      publishedAt: new Date(Date.now() - Math.floor(Math.random() * 30 * 24 * 60 * 60 * 1000)),
      updatedAt: new Date(),
      status,
      viewCount: Math.floor(Math.random() * 1000),
      favoriteCount: Math.floor(Math.random() * 100),
      inquiryCount: Math.floor(Math.random() * 50),
      tags: ['校园', '二手', '实惠', '学生'],
      isNegotiable: Math.random() > 0.5,
      isFreeShipping: Math.random() > 0.7,
      shippingFee: Math.random() > 0.7 ? Math.floor(Math.random() * 20) + 5 : undefined,
      stock: status === ProductStatus.SOLD ? 0 : Math.floor(Math.random() * 5) + 1,
      isReturnable: Math.random() > 0.8,
    };
    
    return mockProduct;
  }

  /**
   * Mock: 创建商品
   */
  private async createMockProduct(productData: ProductFormData): Promise<ProductOperationResult> {
    await this.delay(500);
    
    const mockProduct: Product = {
      id: `product_${Date.now()}`,
      ...productData,
      images: [],
      location: {
        school: productData.school,
        campus: productData.campus,
        address: productData.address,
      },
      publisher: {
        userId: 'current_user',
        username: '当前用户',
        isStudentVerified: true,
        school: productData.school,
      },
      publishedAt: new Date(),
      updatedAt: new Date(),
      status: ProductStatus.ACTIVE,
      viewCount: 0,
      favoriteCount: 0,
      inquiryCount: 0,
      isNegotiable: productData.isNegotiable,
      stock: productData.stock,
      isReturnable: productData.isReturnable,
    };
    
    return {
      success: true,
      message: '商品发布成功',
      product: mockProduct,
    };
  }

  /**
   * Mock: 更新商品
   */
  private async updateMockProduct(id: string, productData: Partial<ProductFormData>): Promise<ProductOperationResult> {
    await this.delay(400);
    
    const mockProducts = this.generateMockProducts(5);
    const product = mockProducts.find(p => p.id === id);
    
    if (!product) {
      return {
        success: false,
        message: '商品不存在',
        error: 'PRODUCT_NOT_FOUND',
      };
    }
    
    // 模拟更新
    Object.assign(product, productData, {
      updatedAt: new Date(),
    });
    
    return {
      success: true,
      message: '商品更新成功',
      product,
    };
  }

  /**
   * Mock: 删除商品
   */
  private async deleteMockProduct(id: string): Promise<ProductOperationResult> {
    await this.delay(300);
    
    return {
      success: true,
      message: '商品删除成功',
    };
  }

  /**
   * Mock: 切换商品状态
   */
  private async toggleMockProductStatus(id: string, status: ProductStatus): Promise<ProductOperationResult> {
    await this.delay(300);
    
    const mockProducts = this.generateMockProducts(5);
    const product = mockProducts.find(p => p.id === id);
    
    if (!product) {
      return {
        success: false,
        message: '商品不存在',
        error: 'PRODUCT_NOT_FOUND',
      };
    }
    
    product.status = status;
    product.updatedAt = new Date();
    
    return {
      success: true,
      message: `商品${status === ProductStatus.ACTIVE ? '上架' : '下架'}成功`,
      product,
    };
  }

  /**
   * Mock: 获取我的商品
   */
  private async getMockMyProducts(params: Omit<ProductQueryParams, 'onlyActive'>): Promise<ProductListResponse> {
    return this.getMockProducts({
      ...params,
      onlyActive: false, // 我的商品显示所有状态
    });
  }

  /**
   * Mock: 搜索商品
   */
  private async searchMockProducts(keyword: string, params?: Omit<ProductQueryParams, 'keyword'>): Promise<ProductListResponse> {
    return this.getMockProducts({
      ...params,
      keyword,
    });
  }

  /**
   * Mock: 获取搜索建议
   */
  private async getMockSearchSuggestions(keyword: string): Promise<ProductSearchSuggestion[]> {
    await this.delay(200);
    
    const suggestions: ProductSearchSuggestion[] = [
      { type: 'keyword', value: '笔记本电脑', count: 15 },
      { type: 'keyword', value: '教材', count: 23 },
      { type: 'category', value: '电子产品', count: 45 },
      { type: 'category', value: '教材书籍', count: 67 },
      { type: 'tag', value: '校园', count: 120 },
    ];
    
    return suggestions.filter(s => 
      s.value.toLowerCase().includes(keyword.toLowerCase())
    );
  }

  /**
   * Mock: 获取商品统计
   */
  private async getMockProductStats(): Promise<ProductStats> {
    await this.delay(400);
    
    return {
      totalProducts: 156,
      activeProducts: 89,
      soldProducts: 42,
      todayNewProducts: 7,
      categoryStats: {
        [ProductCategory.TEXTBOOKS]: 23,
        [ProductCategory.ELECTRONICS]: 34,
        [ProductCategory.CLOTHING]: 18,
        [ProductCategory.DAILY_GOODS]: 27,
        [ProductCategory.SPORTS]: 12,
        [ProductCategory.STATIONERY]: 15,
        [ProductCategory.DORMITORY]: 21,
        [ProductCategory.OTHER]: 6,
      },
    };
  }

  /**
   * Mock: 收藏商品
   */
  private async favoriteMockProduct(productId: string): Promise<ProductOperationResult> {
    await this.delay(300);
    
    return {
      success: true,
      message: '收藏成功',
    };
  }

  /**
   * Mock: 取消收藏
   */
  private async unfavoriteMockProduct(productId: string): Promise<ProductOperationResult> {
    await this.delay(300);
    
    return {
      success: true,
      message: '取消收藏成功',
    };
  }

  /**
   * Mock: 获取我的收藏
   */
  private async getMockMyFavorites(params?: { page?: number; pageSize?: number }): Promise<{
    favorites: ProductFavorite[];
    total: number;
  }> {
    await this.delay(400);
    
    const mockProducts = this.generateMockProducts(10);
    const favorites: ProductFavorite[] = mockProducts.slice(0, 5).map((product, index) => ({
      id: `favorite_${index}`,
      productId: product.id,
      userId: 'current_user',
      favoritedAt: new Date(Date.now() - index * 24 * 60 * 60 * 1000),
      product,
    }));
    
    return {
      favorites,
      total: favorites.length,
    };
  }

  /**
   * 字符串哈希函数
   */
  private hashCode(str: string): number {
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
      const char = str.charCodeAt(i);
      hash = ((hash << 5) - hash) + char;
      hash = hash & hash; // 转换为32位整数
    }
    return Math.abs(hash);
  }

  /**
   * 模拟网络延迟
   */
  private delay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

// 创建全局商品服务实例
export const productService = new ProductService();

export default ProductService;